package cfca.seal.mananger;

import cfca.sadk.algorithm.common.PKIException;
import cfca.sadk.x509.certificate.X509CRL;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CrlManager
{
  private static final Logger log = LoggerFactory.getLogger("web_sys");

  public static boolean offline_crl = true;
  private static Map<String, X509CRL> crlCachePool = new ConcurrentHashMap();
  private static Map<String, Boolean> crlResultPool = new ConcurrentHashMap();

  public static void cacheOrRefreshCrl(String crlRootPath)
    throws Exception
  {
    File crlDir = new File(crlRootPath);
    if (!crlDir.exists()) {
      crlDir.mkdir();
    }
    for (File file : crlDir.listFiles())
      if (file.isDirectory()) {
        X509CRL crl = null;
        String issuerKey = file.getName();
        String crlPath = crlRootPath + File.separator + issuerKey + File.separator + "crl.crl";
        if (new File(crlPath).exists()) {
          crl = getCRLFromPath(crlPath);
          if (crl != null) {
            crlCachePool.put(issuerKey, crl);
            log.info("CRL管理容器开始缓存CRL,key= " + issuerKey);
          }
        }
      }
  }

  public static X509CRL getCRLFromPath(String crlPath) throws IOException, PKIException
  {
    FileInputStream inStream = new FileInputStream(crlPath);
    byte[] crlByte = new byte[inStream.available()];
    inStream.read(crlByte);
    inStream.close();
    return new X509CRL(crlByte);
  }

  public static void updateCrlPool(String issuerKey, X509CRL x509CRL) {
    for (Iterator i = crlResultPool.keySet().iterator(); i.hasNext(); ) {
      String key = (String)i.next();
      if (key.indexOf(issuerKey) >= 0) {
        i.remove();
      }
    }
    crlCachePool.put(issuerKey, x509CRL);
    log.info("CRL管理容器,开始清除CRL验证缓存机制，关键字:" + issuerKey + "并添加新的缓存");
  }

  public static List<X509CRL> getX509CRLList() {
    return new ArrayList(crlCachePool.values());
  }

  public static X509CRL deleteX509CRL(String issuerKey) {
    return (X509CRL)crlCachePool.remove(issuerKey);
  }

  public static X509CRL getX509CRL(String issuerKey) {
    return (X509CRL)crlCachePool.get(issuerKey);
  }
}